package com.infore.maintenance.main.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.infore.common.base.EppPage;
import com.infore.common.base.Msg;
import com.infore.common.base.ResultUtil;
import com.infore.common.base.WrapperHelp;
import com.infore.common.exception.MyException;
import com.infore.common.fw.BaseController;
import com.infore.common.model.dto.TBaseQuerySqlSaveDto;
import com.infore.common.model.entity.TBaseQuerySql;
import com.infore.common.model.entity.vo.TBaseQuerySqlVo;
import com.infore.common.request.query.CheckSqlRequest;
import com.infore.common.request.query.QuerySqlRequest;
import com.infore.common.response.ApiResponse;
import com.infore.common.utils.StringUtils;
import com.infore.maintenance.main.service.TBaseQuerySqlService;
import com.infore.maintenance.main.utils.RedisUtil;
import com.infore.maintenance.main.utils.parsesql.SqlAnalysis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 查询接口SQL模板 前端控制器
 * </p>
 *
 * @author lijh
 * @since 2022-12-01
 */
@RestController
@Api(value = "查询接口SQL模板前端控制器", tags = "查询接口SQL模板前端控制器")
@RequestMapping("/tBaseQuerySql")
public class TBaseQuerySqlController extends BaseController {
	private String prefix = "/tBaseQuerySql";

	@Autowired
	private TBaseQuerySqlService TBaseQuerySqlService;

	@Autowired
	private RedisUtil redisUtil;

	@GetMapping()
	public String TBaseQuerySqlController(){
		return prefix;
	}

	/**
	 * 查询查询接口SQL模板列表
	 * @param tbasequerysqlVo 查询接口SQL模板的vo类
	 * @return Msg<Object> 结果集
	 * @author lijh
	 * @since 2022-12-01
	 */
	@PostMapping("/list")
	@ResponseBody
	@ApiOperation(value = "查询查询接口SQL模板列表", notes = "查询接口SQL模板列表查询 ")
	public Msg<Object> list(TBaseQuerySqlVo tbasequerysqlVo){
		//sql查询条件
		Wrapper<TBaseQuerySql> wrapper = null ;
		try {
			wrapper = (Wrapper<TBaseQuerySql>) WrapperHelp.addCondition(new EntityWrapper<TBaseQuerySql>(), tbasequerysqlVo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error(500,e.getMessage());
		}
		//查询方法
		Page<TBaseQuerySql> eppPage = new EppPage<TBaseQuerySql>(TBaseQuerySqlService,tbasequerysqlVo,wrapper);
		return ResultUtil.successPage(TBaseQuerySqlService.selectPage(eppPage, wrapper));
	}

	/**
	 * 查询查询接口SQL模板列表
	 * @param tBaseQuerySqlSaveDto 查询接口SQL模板
	 * @return Msg<Object> 结果集
	 * @author lijh
	 * @since 2022-12-01
	 */
	@ResponseBody
	@ApiOperation(value = "添加查询接口SQL模板", notes = "查询接口SQL模板新增")
	@RequestMapping(value="/add",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	public Msg<Object> add(@RequestBody TBaseQuerySqlSaveDto tBaseQuerySqlSaveDto){
		Wrapper<TBaseQuerySql> wrapper = new  EntityWrapper<TBaseQuerySql>();
	    wrapper.eq("sql_code", tBaseQuerySqlSaveDto.getSqlCode());
		List<TBaseQuerySql> entityList = TBaseQuerySqlService.selectList(wrapper);
		if(entityList.size()>0) {
			return ResultUtil.error("重复添加");
		}
		TBaseQuerySql tbasequerysql = new TBaseQuerySql();
		BeanUtil.copyProperties(tBaseQuerySqlSaveDto,tbasequerysql);
		//校验SQL
        String executeSql = TBaseQuerySqlService.checkSql(tBaseQuerySqlSaveDto.getEncryptSql());
        tbasequerysql.setExecuteSql(executeSql);

        //校验SQL查询的列名是否与resultColumn返回结果列是否匹配

		boolean ok = TBaseQuerySqlService.checkSqlExecute(tbasequerysql);
		if(ok){
			//插入数据
			tbasequerysql.setCreateTime(new Date());
			tbasequerysql.setCreateUserid("");
			boolean flag = TBaseQuerySqlService.insert(tbasequerysql);
			//放入缓存
			if(flag){
				redisUtil.set(tbasequerysql.getSqlCode(), JSONUtil.toJsonStr(tbasequerysql) );
			}
			return ResultUtil.setResult(flag,tbasequerysql.getId().toString());
		}else{
			throw new MyException("500","请检查参数");
		}
	}





	/**
	  * 更新查询接口SQL模板方法
	  *
	  * @param tbasequerysql 查询接口SQL模板
	  * @return Msg<Object>
	  * @author lijh
	  * @since 2022-12-01
	  */
	@ResponseBody
	@ApiOperation(value = "更新查询接口SQL模板", notes = "查询接口SQL模板更新")
	@RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Msg<Object> edit(@RequestBody TBaseQuerySql tbasequerysql) {
		//旧数据
//		TBaseQuerySql sourceQuerySql = TBaseQuerySqlService.selectById(tbasequerysql.getId());

		String executeSql = TBaseQuerySqlService.checkSql(tbasequerysql.getEncryptSql());
		tbasequerysql.setExecuteSql(executeSql);
		tbasequerysql.setCreateUserid("");
		tbasequerysql.setCreateTime(new Date());
		//插入数据
		boolean flag = TBaseQuerySqlService.updateById(tbasequerysql);
		//更新缓存
		if(flag){
			redisUtil.set(tbasequerysql.getSqlCode(), JSONUtil.toJsonStr(tbasequerysql) );
		}
		return ResultUtil.setResult(flag, tbasequerysql.getId().toString());
	}



	/**
	 * 删除查询接口SQL模板
	 *
	 * @param  id
	 * @return Msg<Object>
	 * @author lijh
	 * @since 2022-12-01
	 */
	@RequestMapping(value = "/del", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "删除查询接口SQL模板", notes = "删除查询接口SQL模板")
	public Msg<Object> del(String id) {
		TBaseQuerySql sourceQuerySql = TBaseQuerySqlService.selectById(id);

		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("id", id);
		boolean flag = TBaseQuerySqlService.deleteByMap(columnMap);
		//删除缓存
		if(flag){
			redisUtil.del(sourceQuerySql.getSqlCode());
		}

		return ResultUtil.setResult(flag);
	}


	/**
	 * 新增或编辑SQL模板方法
	 *
	 * @param tbasequerysql 查询接口SQL模板
	 * @return Msg<Object>
	 * @author lijh
	 * @since 2022-12-01
	 */
	@ResponseBody
	@ApiOperation(value = "新增或编辑SQL模板", notes = "新增或编辑SQL模板")
	@RequestMapping(value = "/addOrEdit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Msg<Object> addOrEdit(@RequestBody TBaseQuerySql tbasequerysql) {
		if(StringUtils.isEmpty(tbasequerysql.getId()) ){
			//新增
			Wrapper<TBaseQuerySql> wrapper = new  EntityWrapper<TBaseQuerySql>();
			wrapper.eq("sql_code", tbasequerysql.getSqlCode());
			List<TBaseQuerySql> entityList = TBaseQuerySqlService.selectList(wrapper);
			if(entityList.size()>0) {
				return ResultUtil.error("重复添加");
			}
			//校验SQL
			String executeSql = TBaseQuerySqlService.checkSql(tbasequerysql.getEncryptSql());
			tbasequerysql.setExecuteSql(executeSql);
			//校验SELECT查询结果列与resultColumn返回结果列是否匹配
			SqlAnalysis.matchSelectSQLAndResultColumn(tbasequerysql.getExecuteSql(),tbasequerysql.getResultColumn());
			//
			boolean ok = TBaseQuerySqlService.checkSqlExecute(tbasequerysql);
			if(ok){
				//插入数据
				tbasequerysql.setCreateTime(new Date());
				tbasequerysql.setCreateUserid("");
				boolean flag = TBaseQuerySqlService.insert(tbasequerysql);
				//放入缓存
				if(flag){
					redisUtil.set(tbasequerysql.getSqlCode(), JSONUtil.toJsonStr(tbasequerysql) );
				}
				return ResultUtil.setResult(flag,tbasequerysql.getId().toString());
			}
		}else{
			//校验SQL
			String executeSql = TBaseQuerySqlService.checkSql(tbasequerysql.getEncryptSql());
			tbasequerysql.setExecuteSql(executeSql);
			//校验SELECT查询结果列与resultColumn返回结果列是否匹配
			SqlAnalysis.matchSelectSQLAndResultColumn(tbasequerysql.getExecuteSql(),tbasequerysql.getResultColumn());
			boolean ok = TBaseQuerySqlService.checkSqlExecute(tbasequerysql);
			if(ok){
				tbasequerysql.setCreateUserid("");
				tbasequerysql.setCreateTime(new Date());
				//修改数据
				boolean flag = TBaseQuerySqlService.updateById(tbasequerysql);
				//更新缓存
				if(flag){
					redisUtil.set(tbasequerysql.getSqlCode(), JSONUtil.toJsonStr(tbasequerysql) );
				}
				return ResultUtil.setResult(flag, tbasequerysql.getId().toString());
			}
		}
		return ResultUtil.error(false);
	}



	@GetMapping("/resultColumn")
	@ResponseBody
	@ApiOperation(value = "返回结果列", notes = "返回结果列")
	public ApiResponse resultColumn(String dataFormat) {
		if("TABLE".equalsIgnoreCase(dataFormat)){
			return ApiResponse.ok("200","");
		}else if("PIE".equals(dataFormat.toUpperCase())){
			return ApiResponse.ok("200","name|标题,value|数值");
		}else if("LINE".equalsIgnoreCase(dataFormat)){
			return ApiResponse.ok("200","xAxis|X轴,yAxis|Y轴");
		}else if("MAP".equalsIgnoreCase(dataFormat)){
			return ApiResponse.ok("200","");
		}
		return ApiResponse.error("500","不存在的数据格式："+dataFormat);
	}


    @PostMapping("/checkSqlResult")
    @ResponseBody
    @ApiOperation(value = "模板校验", notes = "模板校验")
    public Object queryCheck(@RequestBody CheckSqlRequest request) {
        startPage(request);
        return TBaseQuerySqlService.checkSqlResult(request,page.get());
    }

	@GetMapping("/queryResult")
	@ResponseBody
	@ApiOperation(value = "根据配制查询结果", notes = "根据配制查询结果")
	public Object query(QuerySqlRequest request) {
		if(request.getNeedPage()==1 ){
			if(StringUtils.isEmpty(request.getDataFormat()) || "TABLE".equals(request.getDataFormat().toUpperCase())){
				return TBaseQuerySqlService.queryDataByCxpzForPage(request);
			}else{
				throw new MyException("500","分页返回数据格式只能为TABLE");
			}
		}else{
			return TBaseQuerySqlService.queryDataByCxpz(request);
		}
	}

}
